import pkg_resources
pkg_resources.require("SQLObject>=0.8,<=0.10.0")
from turbogears.database import PackageHub
# import some basic SQLObject classes for declaring the data model
# (see http://www.sqlobject.org/SQLObject.html#declaring-the-class)
from sqlobject import SQLObject, SQLObjectNotFound, RelatedJoin, ForeignKey, MultipleJoin
# import some datatypes for table columns from SQLObject
# (see http://www.sqlobject.org/SQLObject.html#column-types for more)
from sqlobject import StringCol, UnicodeCol, IntCol, DateTimeCol, DateCol
from sqlobject import LIKE

__connection__ = hub = PackageHub('bookloantracker')


class Book(SQLObject):
    isbn = UnicodeCol(length=20, default=None)
    title = UnicodeCol(length=80, unique=True)
    edition = UnicodeCol(length=20, default=None)
    description = UnicodeCol(default=None)
    webPage = UnicodeCol(default=None)
    localization = UnicodeCol(length=30, default=None)
    wordKeys = RelatedJoin("WordKeys")
    publisher = ForeignKey("Publisher")
    authors = RelatedJoin("Author")
    loanHistory = MultipleJoin("Loan")

    def _get_isLoaned(self):
        for loan in self.loanHistory:
            if loan.stop is None:
                return True
        return False

    def _get_lastOpenLoan(self):
        for loan in self.loanHistory:
            if loan.stop is None:
                return loan
        return None
        
    def _get_authorStr(self):
        return u'%s' % ",".join([author.name for author in self.authors])
            
    def _get_wordKeysStr(self):
        return u'%s' % ",".join([wordKey.word for wordKey in self.wordKeys])
            


class Publisher(SQLObject):
    name = UnicodeCol(length=80, unique=True)
    books = MultipleJoin("Book")
    webPage = UnicodeCol(default=None)


class Author(SQLObject):
    name = UnicodeCol(length=80, unique=True)
    books = RelatedJoin("Book")
    info = UnicodeCol(default=None)
    webPage = UnicodeCol(default=None)


class WordKeys(SQLObject):
    word = UnicodeCol(length=30, unique=True)
    books = RelatedJoin("Book")


class Loan(SQLObject):
    book = ForeignKey("Book")
    loaner = ForeignKey("Loaner")
    start = DateCol()
    stop = DateCol(default=None)


class Loaner(SQLObject):
    name = UnicodeCol(length=80, unique=True)
    birthDate = DateCol(default=None)
    phoneNumber = UnicodeCol(length=20, default=None)
    email = UnicodeCol(length=80)
    address = UnicodeCol(default=None)
    loanHistory = MultipleJoin("Loan")
